package com.xunk.equipment.service.dnake;

import com.alibaba.fastjson.JSONObject;
import com.xunk.common.core.utils.IdUtils;
import com.xunk.equipment.config.DnakeConfig;
import com.xunk.equipment.config.MQTTClient;
import com.xunk.equipment.service.dnake.vo.DnakeMqttRequestDataMessage;
import com.xunk.equipment.service.dnake.vo.DnakeRequestMqttMessage;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

@Component
public class DnakePublishComponent {

    @Resource
    @Qualifier("MQTT_126")
    MQTTClient client;

    @Autowired
    private DnakeConfig dnakeConfig;

    /**
     * mqtt发布消息
     *
     * @param action          动作
     * @param gatewayDeviceSn 网关sn号
     * @param type            类型system:获取设备信息；system获取设备在线信息
     */
    public void simplePublish(String action, String gatewayDeviceSn, String type) {
        DnakeMqttRequestDataMessage vo = new DnakeMqttRequestDataMessage();
        vo.setAction(action);
        publish(vo, gatewayDeviceSn, type);
    }

    /**
     * mqtt发布消息
     *
     * @param data            data信息
     * @param gatewayDeviceSn 网关sn号
     * @param type            类型system:获取设备信息；system获取设备在线信息
     */
    public void publish(DnakeMqttRequestDataMessage data, String gatewayDeviceSn, String type) {
        MqttMessage message = new MqttMessage();

        data.setUuid(Optional.ofNullable(data.getUuid()).orElseGet(IdUtils::simpleUUID));
        DnakeRequestMqttMessage mqttMessage = new DnakeRequestMqttMessage();
        mqttMessage.setData(data)
                .setFromDev(type)
                .setToDev(gatewayDeviceSn);

        message.setPayload(JSONObject.toJSONString(mqttMessage).getBytes(StandardCharsets.UTF_8));

//        String topic = "/" + productKey + "/" + gatewayDeviceSn + "/get";
        client.publish(String.join("/", "", dnakeConfig.getProductKey(), gatewayDeviceSn, "get"), message);
    }

}
